export default function createMatcher(routes) {
  const pathMap = new Map();
  createRouteMap(routes);
  let current = {
    path: "",
    route: [],
  };
  function createRouteMap(routes, parent) {
    routes.forEach((route) => {
      const path = parent
        ? parent.path + "/" + route.path.replace("/", "")
        : route.path;
      if (!pathMap.has(path)) {
        pathMap.set(path, route);
      }
      if (Array.isArray(route.children)) {
        createRouteMap(route.children, route);
      }
    });
  }
  function addRoutes(routes) {
    createRouteMap(routes);
  }
  function match(path) {
    const routeComponentList = [];
    const pathArr = path.split("/");
    pathArr.forEach((shortName, index) => {
      const shortPath =
        index == 0 ? "/" : pathArr.slice(0, index + 1).join("/");
      console.log(shortPath);
      const route = pathMap.get(shortPath);
      if (route) {
        routeComponentList.push(route.component);
      }
    });
    current.path = path;
    current.route = routeComponentList;
  }
  return {
    addRoutes,
    match,
    current,
  };
}
